#! /usr/bin/python2.7

import os, os.path, sys, time, select, signal
from time import localtime, strftime

gExit = False;
gFout = None;

def indexOfFd(fd, fds):
	idx = 0;
	for ifd in fds:
		if ifd is fd:
			return idx;
		idx = idx + 1;
	return -1;

def listenTo(files, rdeventproc):
	fds = [];
	for fin in files:
		fd = os.open(fin, os.O_RDONLY);
		fds.append(fd);
	
	poller = select.poll();
	for fd in fds:
		poller.register(fd, select.POLLIN);
	global gExit;
	while not gExit:
		try:
			for fd, event in poller.poll(1000):
				idx = indexOfFd(fd, fds);
				if idx >= 0:
					rdeventproc(files[idx], fd);
				else:
					gExit = True;
		except:
			pass;
	
	for fd in fds:
		os.close(fd);

def rdevent_cb(fname_raw, fd):
	timestamp = strftime("%H:%M:%S", localtime());
	
	# idx = fname_raw.find("?");
	# if idx == -1:
	#	fname = fname_raw;
	# else:
	#	fname = fname_raw[:idx];
	fname = fname_raw;
	
	global gFout;
	gFout.write("{0}\n{1}".format(timestamp, fname));
	print "{0}\n{1}".format(timestamp, fname);
	data = os.read(fd, 4 * 1024);
	gFout.write(data);
	print data;
	gFout.write("\n");
	
def on_term(signum, frame):
	print "signal {0} received.\n".format( signum );
	global gExit;
	gExit = True;
		
def main():
	global gFout;
	
	files = ["/pps/services/cellular/radioctrl/status_public?wait,delta,f=power_status", 
			 "/pps/services/cellular/radioctrl/status_cell_public?wait,delta,f=network_service+roaming",
			 "/pps/services/cellular/radioctrl/status_cell_cdma_public?wait,delta,f=network_service+roaming",
			 "/pps/services/cds/cnice/status?wait,delta,f=data_services_status+data_roaming_status+internet+user_enabled_data_roaming",
			 "/pps/services/cds/cnice/status_persistent?wait,delta,f=data_service_mode+data_roaming_mode"];

	
	signal.signal(signal.SIGTERM, on_term);
	signal.signal(signal.SIGINT, on_term);

	if len(sys.argv) < 2:
		print "Usage ppsspy.py <output-file>\n";
		return;	
	
	gFout = open(sys.argv[1], "w");
	listenTo(files, rdevent_cb);
	gFout.close();
			
if __name__ == "__main__":
	main();